<template>
  <div class="home">
    <ul class="goods-list">
      <li v-for="item in dishList" :key="item.id">
        <img :src="item.image" alt="" style="width: 100px;height: 100px;" />
        <div class="goods-info">
          <span>{{ item.name }}</span>
          <span>{{ item.description }}</span>
          <span>¥{{ item.price }}</span>
        </div>

        <button @click="addToCart(item)">加入购物车</button>
      </li>
    </ul>


    <div class="target-element">
      <button @click="showCartPopup">显示购物车</button>
      <div class="animated-element">
        <!-- 引入购物车弹窗组件 -->
        <CartPopup
            :cart-items="cartStore.cartList"
            :is-show="isCartPopupShow"
            @close="closeCartPopup"
            @changeCount="handleChangeCount"
            @settle="handleSettle"
        />
      </div>
    </div>



  </div>
</template>

<script setup>
import { ref ,onMounted} from 'vue';
import CartPopup from '@/views/ShoppingCart/components/CartPopup.vue';
import {useDish} from "@/views/Category/composables/useDish.js";
import {useCartStore} from "@/stores/cartStore.js";
const dishList=useDish().dishList
// 模拟商品数据
// 购物车数据
const cartItems = ref([{}]);
const cartStore = useCartStore()


// 购物车弹窗显示状态
const isCartPopupShow = ref(false);

// 显示购物车弹窗
const showCartPopup = () => {
  isCartPopupShow.value = true;
};

// 关闭购物车弹窗
const closeCartPopup = () => {
  isCartPopupShow.value = false;
};

// 处理商品数量变化
const handleChangeCount = ({ id, type }) => {
  const item = cartItems.value.find((item) => item.id === id);
  if (item) {
    if (type === 'increase') {
      item.count++;
    } else if (type === 'decrease' && item.count > 1) {
      item.count--;
    }
  }
};

// 处理加入购物车
const addToCart = (item) => {
  const existItem = cartItems.value.find((cartItem) => cartItem.id === item.id);
  if (existItem) {
    existItem.count++;
  } else {
    cartItems.value.push({ ...item, count: 1 });
  }
  showCartPopup();
};

// 处理结算
const handleSettle = () => {
  alert('结算逻辑，可跳转到结算页面等');
  closeCartPopup();
};
</script>

<style scoped>
.home {
  padding: 20px;
}

.goods-list {
  list-style: none;
  padding: 0;
  margin-bottom: 20px;
}

.goods-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.goods-info {
  display: flex;
  flex-direction: column;
}

button {
  padding: 6px 12px;
  cursor: pointer;
}

/* 使用示例 */
.target-element {
  /* 假设这是目标控件 */
  position: relative;
  width: 100px;
  height: 100px;
  background: #ffb302;
}
.animated-element {
  /* 动画元素需要相对于目标控件定位 */
  position: absolute;
  top: -100%; /* 初始在目标控件下方 */
  left: 0;   /* 初始在目标控件左侧 */

  /* 应用动画 */
  animation: slideToTopRight 0.8s ease-out forwards;
  width: 100px;
  height: 100px;
  background: #cf4444;
}

@keyframes slideToTopRight {
  from {
    /* 起始位置：目标控件左下方 */
    transform: translateY(100%);
  }
  to {
    /* 结束位置：目标控件位置 */
    transform: translateY(0);
  }
}

</style>